#Downloaded from the internet. Source: http://code.google.com/p/techproj/source/browse/trunk/IntroAI/hw2/timer.py
import time

class TimeoutException:
  """
  This exception is thrown when the time is up in the timer.
  """

  def __init__(self, time_limit, actual_time):
    self.time_limit = time_limit
    self.actual_time = actual_time

class Timer:
  """
  This timer class can be called at regualr intervals to check if the time is
  up, and if so it throws an exception to halt execution.
  """

  SAFETY_FACTOR = 0.9
  SAFETY_MARGIN_SECONDS = 0.5

  def __init__(self, limit):
    self.limit = limit
    self.start = time.clock()

  def check(self):
    if not self.isTimeLeft():
      raise TimeoutException(self.limit, time.clock() - self.start)

  def isTimeLeft(self):
    used_time = time.clock() - self.start
    limit = max(self.limit * self.SAFETY_FACTOR,
                self.limit - self.SAFETY_MARGIN_SECONDS)
    return used_time <= limit